﻿using Identity.API.Infrastructure;
using Identity.API.Model;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;

namespace Microsoft.eShopOnDapr.Services.Ordering.API.Infrastructure.Repositories;

public class UserInfoRepository : IUserInfoRepository
{
    private readonly UserInfoDbContext _userContext;

    public UserInfoRepository(UserInfoDbContext userContext)
    {
        _userContext = userContext ?? throw new ArgumentNullException(nameof(userContext));

        _userContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
    }

    public Task<UserInfo?> GetUserInfoByIdAsync(Guid userId)
    {
        return _userContext.UserInfos
      .Where(o => o.Id == userId)
      .SingleOrDefaultAsync();
    }

    public async Task<UserInfo?> GetUserInfoByOpenIdAsync(string openId)
    {
        var userInfo = await _userContext.UserInfos
      .Where(o => o.OpenId == openId)
      .SingleOrDefaultAsync();
        if (userInfo != null)
        {
            userInfo.LastDate = DateTime.Now;
            _userContext.Update(userInfo);

            _userContext.SaveChangesAsync();

        }
        return userInfo;
    }

    public async Task<UserInfo?> AddOrGetUserInfoAsync(UserInfo user)
    {
        _userContext.Add(user);

        try
        {
            await _userContext.SaveChangesAsync();
            return user;
        }
        catch (DbUpdateException ex)
            when ((ex.InnerException as SqlException)?.Number == 2627)
        {
            return (await GetUserInfoByIdAsync(user.Id))!;
        }
    }

    public Task UpdateUserInfoAsync(UserInfo user)
    {
        _userContext.Update(user);

        return _userContext.SaveChangesAsync();
    }
}
